#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/11/8 14:47
# @Author  : zy
# @File    : async_point_img.py

"""
 pip install pillow
 pip install pymongo

功能： 从本地文件目录中读取图片,图片目录名为 数据库中对应键值,将多张图片组合为一张以Id为文件名的图片，存入数据库中

"""

import asyncio

from pymongo import AsyncMongoClient
from gridfs import AsyncGridFS
from units import *

# 连接数据库
client = AsyncMongoClient(host='49.232.233.253', port=27017)
work = client.work
address = work.address
fs = AsyncGridFS(work)


# 从数据库中拿到 点位ID
async def point_id(point_name):
    point: dict = await address.find_one({'point': point_name}, {'_id': 1, 'point': 1})
    print(point_name, point)
    return point['_id']


# 处理点位图片
async def point_img(path: Path, target='store'):
    new_image = Image.new('RGBA', (1600, 1000), color='white')
    idx = 0
    for pic in path.glob('*'):
        if idx > 1:
            break
        img = Image.open(pic)
        img = img.resize(size=(800, 1000))
        new_image.paste(img, (idx * 800, 0))
        idx += 1

    _id = await point_id(point_name=path.name)

    if target == 'store':
        new_image.save(Path('tmp/point_img') / f'{_id}.png')  # 存储路径

    elif target == 'fs':
        await fs.put(data=FILE.img_to_bytes(new_image), filename=f'{_id}.png')


async def main():
    for path in (p for p in Path('tmp/有害垃圾点位').glob('*') if p.is_dir()):  # 存储图片的路径
        await point_img(path=path, target='fs')  # 存入数据库
    print('ok....')


# 显示所有文件名
async def filenames_show():
    files = fs.find()

    for f in await files.to_list():
        print(f.filename)


# 显示指定文件的图片
async def file_appear():
    file = await fs.get_version(filename='p-1002.png')
    byte = await file.read()

    im = Image.open(fp=BytesIO(byte))
    im.show()


if __name__ == '__main__':
    asyncio.run(main())
    # asyncio.run(filenames_show())
    # asyncio.run(file_appear())
    ...
